<template>
  <div class="app-container">
    <!-- 左侧树形菜单 -->
    <splitpanes
      :horizontal="this.$store.getters.device === 'mobile'"
      class="default-theme"
    >
      <pane size="16">
        <el-col>
          <div class="head-container">
            <el-input
              v-model="projectName"
              placeholder="请输入培训项目"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="projectOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>
    </splitpanes>
    <!-- 主内容区 -->
    <el-col :span="20" style="padding: 20px">
      <!-- 高级搜索表单 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="姓名">
          <el-input
            v-model="queryParams.studentName"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-input
            v-model="queryParams.sex"
            placeholder="请输入性别"
            clearable
          />
        </el-form-item>
        <el-form-item label="证件编号">
          <el-input
            v-model="queryParams.idNumber"
            placeholder="请输入证件编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="培训类型">
          <el-select
            v-model="queryParams.trainingType"
            placeholder="请选择培训类型"
            clearable
          >
            <el-option label="新训" value="new" />
            <el-option label="复训" value="retrain" />
            <el-option label="转岗" value="transfer" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
          />
        </el-form-item>
        <el-form-item label="单位名称">
          <el-input
            v-model="queryParams.unitName"
            placeholder="请输入单位名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="报名时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="缴费状态">
          <el-select
            v-model="queryParams.paymentStatus"
            placeholder="请选择缴费状态"
            clearable
          >
            <el-option label="已缴费" value="paid" />
            <el-option label="未缴费" value="unpaid" />
          </el-select>
        </el-form-item>
        <el-form-item label="档案状态">
          <el-select
            v-model="queryParams.recordStatus"
            placeholder="请选择档案状态"
            clearable
          >
            <el-option label="有档案" value="has" />
            <el-option label="无档案" value="no" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交状态">
          <el-select
            v-model="queryParams.submitStatus"
            placeholder="请选择提交状态"
            clearable
          >
            <el-option label="已提交" value="submitted" />
            <el-option label="未提交" value="not_submitted" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 操作按钮栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="24">
          <!-- 主要操作按钮 -->
          <el-button-group>
            <el-button type="primary">报名列表</el-button>
            <el-button
              type="primary"
              plain
              @click="handleExport"
              v-hasPermi="['training:registration:export']"
              >导出</el-button
            >
          </el-button-group>
          <el-button-group style="margin-left: 10px">
            <el-button type="primary">新增报名</el-button>
            <el-button type="primary" plain @click="handleAddPersonal"
              >新增个人报名</el-button
            >
            <el-button type="primary" plain @click="handleAddGroup"
              >新增集体报名</el-button
            >
            <el-button type="primary" plain @click="handleImport"
              >导入报名信息</el-button
            >
          </el-button-group>

          <el-button-group style="margin-left: 10px">
            <el-button type="success">缴费</el-button>
            <el-button type="success" plain @click="handleQRCode"
              >缴费二维码</el-button
            >
            <el-button type="success" plain @click="handleTransfer"
              >转账缴费</el-button
            >
          </el-button-group>

          <el-button-group style="margin-left: 10px">
            <el-button type="warning" plain @click="toggleSearch"
              >隐藏搜索</el-button
            >
            <el-button type="warning" plain @click="handleRefresh"
              >刷新</el-button
            >
            <el-button type="warning" plain @click="toggleColumns"
              >隐藏/排序列</el-button
            >
          </el-button-group>
        </el-col>
        <el-col :span="24" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">报名信息</el-button>
            <el-button type="primary" plain @click="handleView()"
              >查看详情</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleEdit()"
              :disabled="single"
              >修改</el-button
            >
            <el-button type="primary" plain @click="handleBatchDelete"
              >删除</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleRemark"
              :disabled="single"
              >报名备注</el-button
            >
            <el-button type="primary" plain @click="handleExportTable"
              >导出申请表</el-button
            >
          </el-button-group>
        </el-col>
        <el-col :span="24" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">档案</el-button>
            <el-button type="primary" plain @click="handleExportTest1" :disabled="ids.length !== 0"
              >档案扫描</el-button
            >
            <el-button type="primary" plain @click="handleExportTest2" :disabled="ids.length === 0"
              >档案上传</el-button
            >
            <el-button type="primary" plain @click="handleExportTest2" :disabled="ids.length === 0"
              >档案查看</el-button
            >
          </el-button-group>
          <el-button-group style="margin-left: 10px">
            <el-button type="success">退款</el-button>
            <el-button type="success" plain @click="handleAddPersonal"
              >发起退费</el-button
            >
            <el-button type="success" plain @click="handleAddGroup"
              >取消退费</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>

      <!-- 新增个人弹窗 -->
      <el-dialog
        title="新增个人报名"
        :visible.sync="dialogVisible"
        width="1000px"
        @close="resetForm"
        class="dialog-person-registration"
        :close-on-click-modal="false"
      >
        <el-form
          :model="form"
          label-width="120px"
          :rules="addPersonRules"
          ref="form"
        >
          <!-- 人员基本信息 -->

          <el-divider content-position="left">人员基本信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名项目" prop="projectId">
                <el-select
                  v-model="form.projectId"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getFlattenedProjectOptions()"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="培训班" prop="trainingClass">
                <el-select
                  v-model="form.trainingClass"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    label="特设培训班"
                    value="specialClass"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训类别" prop="trainingType">
                <el-radio-group v-model="form.trainingType">
                  <el-radio label="1">新训</el-radio>
                  <el-radio label="2">复训</el-radio>
                  <el-radio label="3">补办换证</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="studentName">
                <el-input
                  v-model="form.studentName"
                  placeholder="请输入姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input
                  v-model="form.phonenumber"
                  placeholder="请输入手机号码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证件类型" prop="certificateType">
                <el-select
                  v-model="form.certificateType"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="身份证" value="idCard"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证件编号" prop="idNumber">
                <el-input
                  v-model="form.idNumber"
                  placeholder="请输入证件号码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证件有效期" prop="idValidDate">
                <el-date-picker
                  v-model="form.idValidDate"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员类型" prop="userType">
                <el-input
                  v-model="form.userType"
                  placeholder="请输入人员类型"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月" prop="birthDate">
                <el-date-picker
                  v-model="form.birthDate"
                  type="date"
                  placeholder="请选择出生年月"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-select
                  v-model="form.nation"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="汉族" value="Han"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务" prop="position">
                <el-input
                  v-model="form.position"
                  placeholder="请输入职务"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学历" prop="qualification">
                <el-select
                  v-model="form.qualification"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="本科" value="bachelor"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="graduatedFrom">
                <el-input
                  v-model="form.graduatedFrom"
                  placeholder="请输入毕业院校"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="所学专业" prop="major">
                <el-input
                  v-model="form.major"
                  placeholder="请输入所学专业"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input
                  type="textarea"
                  :rows="3"
                  v-model="form.address"
                  placeholder="请输入详细地址"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="邮编" prop="postCode">
                <el-input
                  v-model="form.postCode"
                  placeholder="请输入邮编"
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="传真" prop="fax">
                <el-input
                  v-model="form.fax"
                  placeholder="请输入传真"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="email">
                <el-input
                  v-model="form.email"
                  placeholder="请输入电子邮箱"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工作时间" prop="workPeriod">
                <el-date-picker
                  v-model="form.workPeriod"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM"
                  format="yyyy-MM"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作单位" prop="workUnit">
                <el-input
                  v-model="form.workUnit"
                  placeholder="请输入工作单位"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="工作简历" prop="workResume">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="form.workResume"
                ></el-input>
                <div style="margin-top: 10px">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="addPersonWorkExperience"
                    >添加工作经历</el-button
                  >
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 单位信息 -->
          <el-divider content-position="left"> 单位信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位名称" prop="unitName">
                <el-input
                  v-model="form.unitName"
                  placeholder="请输入单位名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位统一信用代码" prop="socialCreditCode">
                <el-input
                  v-model="form.socialCreditCode"
                  placeholder="请输入统一信用代码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属区域" prop="administrativeArea">
                <el-select
                  v-model="form.administrativeArea"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    label="四川省-成都市-武侯区"
                    value="Sichuan-Chengdu-Wuhou"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在单位性质" prop="unitNature">
                <el-select
                  v-model="form.unitNature"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="企业" value="enterprise"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人姓名" prop="contact">
                <el-input
                  v-model="form.contact"
                  placeholder="请输入联系人姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="unitPhonenumber">
                <el-input
                  v-model="form.unitPhonenumber"
                  placeholder="请输入手机号码"
                ></el-input> </el-form-item
            ></el-col>
          </el-row>

          <!-- 档案缺失情况 -->
          <el-divider content-position="left">档案缺失情况</el-divider>

          <el-form-item prop="recordMissing">
            <el-checkbox-group
              v-model="form.recordMissing"
              @change="handleArchiveMissingChange"
            >
              <el-checkbox label="全缺"></el-checkbox>
              <el-checkbox label="照片"></el-checkbox>
              <el-checkbox label="申请表"></el-checkbox>
              <el-checkbox label="身份证"></el-checkbox>
              <el-checkbox label="学历证明"></el-checkbox>
              <el-checkbox label="体检证明"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 协议缺失情况 -->
          <el-divider content-position="left">协议缺失情况</el-divider>

          <el-form-item prop="agreementStatus">
            <el-checkbox v-model="form.agreementStatus">缺协议</el-checkbox>
          </el-form-item>

          <!-- 备注 -->
          <el-divider content-position="left">备注</el-divider>

          <el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              :rows="3"
              v-model="form.remarks"
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部按钮 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPersonForm('form')"
            >确定</el-button
          >
        </div>
      </el-dialog>

      <!-- 报名导入弹窗 -->
      <el-dialog
        :title="importTitle"
        :visible.sync="importOpen"
        width="600px"
        class="dialog-import-personal"
      >
        <el-form
          ref="importForm"
          :model="importForm"
          :rules="importRules"
          label-width="100px"
        >
          <!-- 模板下载 -->
          <el-form-item label="报名信息模板">
            <el-button size="small" @click="downloadTemplate"
              >下载报名信息模板</el-button
            >
          </el-form-item>
          <el-form-item label="上传报名信息">
            <el-upload
              ref="upload"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="uploadHeaders"
              :action="uploadUrl"
              :disabled="uploadSuccess"
              :on-progress="handleGroupUploadProgress"
              :on-success="handleGroupUploadSuccess"
              :on-error="handleGroupUploadError"
              :auto-upload="false"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">上传报名信息</el-button>
              <div slot="tip" class="el-upload__tip">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; margin-left: 10px"
                  @click="downloadTemplate"
                >
                  下载模板
                </el-link>
              </div>
            </el-upload>

            <!-- 上传状态显示 -->
            <div
              v-if="uploadSuccess"
              style="color: #67c23a; font-size: 12px; margin-top: 5px"
            >
              已上传：{{ uploadedFileName }} 100% 上传成功
              <el-link
                type="danger"
                style="margin-left: 10px"
                @click="handleRemove()"
                >删除</el-link
              >
            </div>
          </el-form-item>

          <!-- 上传状态 -->
          <div
            v-if="importSuccess"
            style="color: #67c23a; font-size: 12px; margin-bottom: 10px"
          >
            已上传：{{ importedFileName }} 100% 上传成功
            <el-link
              type="danger"
              style="margin-left: 10px"
              @click="handleImportRemove()"
              >删除</el-link
            >
          </div>
        </el-form>

        <div slot="footer">
          <el-button @click="cancelImport">取消</el-button>
          <el-button type="primary" @click="submitImport">导入</el-button>
        </div>
      </el-dialog>

      <!-- 新增集体报名弹窗 -->
      <el-dialog
        :title="groupTitle"
        :visible.sync="groupOpen"
        width="1000px"
        class="dialog-collective-registration"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
      >
        <el-tabs v-model="groupActiveTab" type="border-card">
          <!-- 单位信息标签页 -->
          <el-tab-pane label="单位信息" name="unitInfo">
            <div v-if="groupActiveTab === 'unitInfo'">
              <el-form
                ref="groupForm"
                :model="groupForm"
                :rules="groupRules"
                label-width="120px"
              >
                <el-divider content-position="left">单位信息</el-divider>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="单位名称" prop="unitName">
                      <el-input
                        v-model="groupForm.unitName"
                        placeholder="请输入单位名称"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="统一信用代码"
                      prop="creditCode"
                      label-width="120px"
                    >
                      <el-input
                        v-model="groupForm.creditCode"
                        placeholder="请输入统一信用代码"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="所属区域" prop="region">
                      <el-select
                        v-model="groupForm.region"
                        placeholder="请选择所属区域"
                        style="width: 100%"
                      >
                        <el-option
                          label="四川省-成都市-武侯区"
                          value="sichuan-chengdu-wuhou"
                        />
                        <el-option
                          label="四川省-成都市-锦江区"
                          value="sichuan-chengdu-jinjiang"
                        />
                        <el-option
                          label="四川省-成都市-青羊区"
                          value="sichuan-chengdu-qingyang"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="单位性质"
                      prop="unitType"
                      label-width="120px"
                    >
                      <el-select
                        v-model="groupForm.unitType"
                        placeholder="请选择单位性质"
                        style="width: 100%"
                      >
                        <el-option label="企业" value="enterprise" />
                        <el-option label="事业单位" value="public" />
                        <el-option label="社会组织" value="organization" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="联系人姓名" prop="contactName">
                      <el-input
                        v-model="groupForm.contactName"
                        placeholder="请输入联系人姓名"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="手机号码"
                      prop="phone"
                      label-width="120px"
                    >
                      <el-input
                        v-model="groupForm.phone"
                        placeholder="请输入手机号码"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 人员信息标签页 -->
          <el-tab-pane label="添加人员" name="personInfo">
            <div v-if="groupActiveTab === 'personInfo'">
              <el-form
                ref="personForm"
                :model="personForm"
                :rules="addPersonRules"
                label-width="100px"
              >
                <el-divider content-position="left">人员基本信息</el-divider>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="报名项目" prop="projectId">
                      <el-select
                        v-model="personForm.projectId"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="item in getFlattenedProjectOptions()"
                          :key="item.id"
                          :label="item.label"
                          :value="item.id"
                          :disabled="item.disabled"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="培训班" prop="trainingClass">
                      <el-select
                        v-model="personForm.trainingClass"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option
                          label="特设培训班"
                          value="specialClass"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="培训类别" prop="trainingType">
                      <el-radio-group v-model="personForm.trainingType">
                        <el-radio label="1">新训</el-radio>
                        <el-radio label="2">复训</el-radio>
                        <el-radio label="3">补办换证</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="姓名" prop="studentName">
                      <el-input v-model="personForm.studentName" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号码" prop="phonenumber">
                      <el-input v-model="personForm.phonenumber" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="证件类型" prop="certificateType">
                      <el-select
                        v-model="personForm.certificateType"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option label="身份证" value="idCard"></el-option>
                        <el-option label="护照" value="passport"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="证件编号" prop="idNumber">
                      <el-input
                        v-model="personForm.idNumber"
                        placeholder="请输入证件号码"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item
                      label="证件有效期"
                      prop="idValidDate"
                      style="width: 100%"
                    >
                      <el-date-picker
                        v-model="personForm.idValidDate"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="人员类型" prop="userType">
                      <el-input
                        v-model="personForm.userType"
                        placeholder="请输入人员类型"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="性别" prop="sex">
                      <el-radio-group v-model="personForm.sex">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="出生年月" prop="birthDate">
                      <el-date-picker
                        v-model="personForm.birthDate"
                        type="date"
                        placeholder="请选择出生年月"
                        value-format="yyyy-MM-dd"
                        format="yyyy-MM-dd"
                        style="width: 100%"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="民族" prop="nation">
                      <el-select
                        v-model="personForm.nation"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option label="汉族" value="Han"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="职务" prop="position">
                      <el-input
                        v-model="personForm.position"
                        placeholder="请输入职务"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="学历" prop="qualification">
                      <el-select
                        v-model="personForm.qualification"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option label="本科" value="bachelor"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="邮编" prop="postCode">
                      <el-input
                        v-model="form.postCode"
                        placeholder="请输入邮编"
                      ></el-input> </el-form-item
                  ></el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="毕业院校" prop="school">
                      <el-input
                        v-model="personForm.school"
                        placeholder="请输入毕业院校"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所学专业" prop="major">
                      <el-input
                        v-model="personForm.major"
                        placeholder="请输入所学专业"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="传真" prop="fax">
                      <el-input
                        v-model="personForm.fax"
                        placeholder="请输入传真"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="电子邮箱" prop="email">
                      <el-input
                        v-model="personForm.email"
                        placeholder="请输入电子邮箱"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="地址" prop="address">
                      <el-input
                        type="textarea"
                        :rows="3"
                        v-model="personForm.address"
                        placeholder="请输入详细地址"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="工作时间" prop="workPeriod">
                      <el-date-picker
                        v-model="personForm.workPeriod"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM"
                        format="yyyy-MM"
                        style="width: 100%"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="工作单位" prop="workUnit">
                      <el-input
                        v-model="personForm.workUnit"
                        placeholder="请输入工作单位"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="工作简历" prop="workResume">
                      <el-input
                        type="textarea"
                        :rows="4"
                        v-model="personForm.workResume"
                      ></el-input>
                      <div style="margin-top: 10px">
                        <el-button
                          type="primary"
                          size="mini"
                          @click="addWorkExperience"
                          >添加工作经历</el-button
                        >
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 已添加人员列表标签页 -->
          <el-tab-pane label="已添加人员" name="addedPersons">
            <div v-if="groupActiveTab === 'addedPersons'">
              <el-table :data="personList" max-height="400">
                <el-table-column
                  prop="studentName"
                  label="姓名"
                  width="100"
                ></el-table-column>
                <el-table-column
                  prop="phonenumber"
                  label="手机号"
                  width="120"
                ></el-table-column>
                <el-table-column
                  prop="idNumber"
                  label="证件号"
                  width="180"
                ></el-table-column>
                <el-table-column label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="removePerson(scope.$index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px; color: #999">
                已添加 {{ personList.length }} 名人员
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div slot="footer">
          <el-button v-if="groupActiveTab === 'unitInfo'" @click="cancelGroup"
            >取消</el-button
          >
          <el-button
            v-if="groupActiveTab === 'unitInfo'"
            type="primary"
            @click="nextStep"
            >下一步</el-button
          >

          <el-button v-if="groupActiveTab === 'personInfo'" @click="prevStep"
            >上一步</el-button
          >
          <el-button
            v-if="groupActiveTab === 'personInfo'"
            @click="continueAddPerson"
            >继续添加</el-button
          >
          <el-button
            v-if="groupActiveTab === 'personInfo'"
            type="primary"
            @click="finishGroupRegistration"
            >完成</el-button
          >

          <el-button
            v-if="groupActiveTab === 'addedPersons'"
            @click="groupActiveTab = 'personInfo'"
            >返回添加</el-button
          >
          <el-button
            v-if="groupActiveTab === 'addedPersons'"
            type="primary"
            @click="finishGroupRegistration"
            >完成</el-button
          >
        </div>
      </el-dialog>

      <!-- 报名备注弹出框 -->
      <el-dialog
        :title="remarkTitle"
        :visible.sync="remarkVisible"
        width="800px"
        @close="resetRemarkForm"
        class="dialog-remark"
      >
        <el-form ref="remarkForm" :model="remarkForm" label-width="80px">
          <!-- 备注输入框 -->
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="remarkForm.remarks"
              type="textarea"
              :rows="4"
              placeholder="请输入备注内容"
              style="width: 100%"
            ></el-input>
          </el-form-item>

          <!-- 备注历史记录 -->
          <el-form-item label="备注历史">
            <el-table
              :data="remarkHistory"
              border
              style="width: 100%"
              :show-header="true"
            >
              <el-table-column prop="time" label="时间" width="200">
                <template slot-scope="scope">
                  {{ scope.row.time }}
                </template>
              </el-table-column>
              <el-table-column prop="operator" label="备注人" width="150">
                <template slot-scope="scope">
                  {{ scope.row.operator }}
                </template>
              </el-table-column>
              <el-table-column prop="content" label="备注" min-width="300">
                <template slot-scope="scope">
                  {{ scope.row.content }}
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="remarkVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemark">提交</el-button>
        </div>
      </el-dialog>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="registrationList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="studentName" />
        <el-table-column
          label="证件编号"
          align="center"
          prop="idNumber"
          width="120px"
        />
        <el-table-column label="性别" align="center" prop="sex" />
        <el-table-column
          label="电话"
          align="center"
          prop="phonenumber"
          width="120px"
        />
        <el-table-column
          label="单位名称"
          align="center"
          prop="unitName"
          width="120px"
        />
        <el-table-column label="联系人" align="center" prop="contact" />
        <el-table-column
          label="联系电话"
          align="center"
          prop="unitPhonenumber"
          width="120px"
        />
        <el-table-column label="报名项目" align="center" prop="projectMap" />
        <!-- <el-table-column label="教学班" align="center" prop="class" /> -->
        <el-table-column label="缴费状态" align="center" prop="paymentStatus">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.paymentStatus === 'paid' ? 'success' : 'danger'"
            >
              {{ scope.row.paymentStatus === "paid" ? "已缴费" : "未缴费" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="档案状态" align="center" prop="recordStatus">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.recordStatus === 'has' ? 'success' : 'danger'"
            >
              {{ scope.row.recordStatus === "has" ? "有档案" : "无档案" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="档案缺失情况" align="center" prop="recordId" />

        <el-table-column label="提交状态" align="center" prop="submitStatus">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.submitStatus === 'submitted' ? 'success' : 'danger'
              "
            >
              {{
                scope.row.submit === "submitted" ||
                scope.row.submit === "待使用"
                  ? "已提交"
                  : "未提交"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="报名时间"
          align="center"
          prop="createTime"
          width="160px"
        />
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button size="mini" type="text" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleExportForm(scope.row)"
              >导出报名表</el-button
            >
            <el-button size="mini" type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 修改弹窗 -->
      <el-dialog :title="title" :visible.sync="open" width="1000px">
        <el-form
          ref="form"
          :model="form"
          :rules="addPersonRules"
          label-width="80px"
        >
          <el-divider content-position="left">人员基本信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名项目" prop="projectId">
                <el-select
                  v-model="form.projectId"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getFlattenedProjectOptions()"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="培训班" prop="trainingClass">
                <el-select
                  v-model="form.trainingClass"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    label="特设培训班"
                    value="specialClass"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训类别" prop="trainingType">
                <el-radio-group v-model="form.trainingType">
                  <el-radio label="1">新训</el-radio>
                  <el-radio label="2">复训</el-radio>
                  <el-radio label="3">补办换证</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="studentName">
                <el-input v-model="form.studentName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input
                  v-model="form.phonenumber"
                  placeholder="请输入手机号码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证件类型" prop="certificateType">
                <el-select
                  v-model="form.certificateType"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="身份证" value="idCard"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证件编号" prop="idNumber">
                <el-input
                  v-model="form.idNumber"
                  placeholder="请输入证件号码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="证件有效期"
                prop="idValidDate"
                label-width="85px"
              >
                <el-date-picker
                  v-model="form.idValidDate"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员类型" prop="userType">
                <el-input
                  v-model="form.userType"
                  placeholder="请输入人员类型"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月" prop="birthDate">
                <el-date-picker
                  v-model="form.birthDate"
                  type="date"
                  placeholder="请选择出生年月"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-select
                  v-model="form.nation"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="汉族" value="Han"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务" prop="position">
                <el-input
                  v-model="form.position"
                  placeholder="请输入职务"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学历" prop="qualification">
                <el-select
                  v-model="form.qualification"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="本科" value="bachelor"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="graduatedFrom">
                <el-input
                  v-model="form.school"
                  placeholder="请输入毕业院校"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="所学专业" prop="major">
                <el-input
                  v-model="form.major"
                  placeholder="请输入所学专业"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input
                  type="textarea"
                  :rows="3"
                  v-model="form.address"
                  placeholder="请输入详细地址"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="邮编" prop="postCode">
                <el-input
                  v-model="form.postCode"
                  placeholder="请输入邮编"
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="传真" prop="fax">
                <el-input
                  v-model="form.fax"
                  placeholder="请输入传真"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="email">
                <el-input
                  v-model="form.email"
                  placeholder="请输入电子邮箱"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工作时间" prop="workPeriod">
                <el-date-picker
                  v-model="form.workPeriod"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM"
                  format="yyyy-MM"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作单位" prop="workUnit">
                <el-input
                  v-model="form.workUnit"
                  placeholder="请输入工作单位"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="工作简历" prop="workResume">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="form.workResume"
                ></el-input>
                <div style="margin-top: 10px">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="addPersonWorkExperience"
                    >添加工作经历</el-button
                  >
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">单位信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位名称" prop="unitName">
                <el-input
                  v-model="form.unitName"
                  placeholder="请输入单位名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="单位统一信用代码"
                prop="socialCreditCode"
                label-width="150px"
              >
                <el-input
                  v-model="form.socialCreditCode"
                  placeholder="请输入统一信用代码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属区域" prop="administrativeArea">
                <el-select
                  v-model="form.administrativeArea"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    label="四川省-成都市-武侯区"
                    value="Sichuan-Chengdu-Wuhou"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="所在单位性质"
                prop="unitNature"
                label-width="150px"
              >
                <el-select
                  v-model="form.unitNature"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option label="企业" value="enterprise"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="联系人姓名"
                prop="contact"
                label-width="85px"
              >
                <el-input
                  v-model="form.contact"
                  placeholder="请输入联系人姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="手机号码"
                prop="unitPhonenumber"
                label-width="150px"
              >
                <el-input
                  v-model="form.unitPhonenumber"
                  placeholder="请输入手机号码"
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <!-- 档案缺失情况 -->
          <el-divider content-position="left">档案缺失情况</el-divider>

          <el-form-item>
            <el-checkbox-group
              v-model="form.recordMissing"
              @change="handleArchiveMissingChange"
            >
              <el-checkbox label="全缺"></el-checkbox>
              <el-checkbox label="照片"></el-checkbox>
              <el-checkbox label="申请表"></el-checkbox>
              <el-checkbox label="身份证"></el-checkbox>
              <el-checkbox label="学历证明"></el-checkbox>
              <el-checkbox label="体检证明"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 协议缺失情况 -->
          <el-divider content-position="left">协议缺失情况</el-divider>

          <el-form-item>
            <el-checkbox v-model="form.agreementStatus">缺协议</el-checkbox>
          </el-form-item>

          <!-- 备注 -->
          <el-divider content-position="left">备注</el-divider>

          <el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              :rows="3"
              v-model="form.remarks"
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 查看按钮对应的弹窗内容 -->
      <el-dialog :title="title" :visible.sync="openLook" width="1000px">
        <el-form ref="form" :model="form" label-width="80px">
          <el-divider content-position="left">人员基本信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名项目" prop="projectId">
                <el-select
                  v-model="form.projectId"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option
                    v-for="item in getFlattenedProjectOptions()"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="培训班" prop="trainingClass">
                <el-select
                  v-model="form.trainingClass"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option
                    label="特设培训班"
                    value="specialClass"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训类别" prop="trainingType">
                <el-radio-group v-model="form.trainingType" disabled>
                  <el-radio label="1">新训</el-radio>
                  <el-radio label="2">复训</el-radio>
                  <el-radio label="3">补办换证</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="studentName">
                <el-input v-model="form.studentName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input
                  v-model="form.phonenumber"
                  placeholder="请输入手机号码"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证件类型" prop="certificateType">
                <el-select
                  v-model="form.certificateType"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option label="身份证" value="idCard"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证件编号" prop="idNumber">
                <el-input
                  v-model="form.idNumber"
                  placeholder="请输入证件号码"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="证件有效期"
                prop="idValidDate"
                label-width="85px"
              >
                <el-date-picker
                  v-model="form.idValidDate"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  disabled
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员类型" prop="userType">
                <el-input
                  v-model="form.userType"
                  placeholder="请输入人员类型"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex" disabled>
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月" prop="birthDate">
                <el-date-picker
                  v-model="form.birthDate"
                  type="date"
                  placeholder="请选择出生年月"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  style="width: 100%"
                  disabled
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-select
                  v-model="form.nation"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option label="汉族" value="Han"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务" prop="position">
                <el-input
                  v-model="form.position"
                  placeholder="请输入职务"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学历" prop="qualification">
                <el-select
                  v-model="form.qualification"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option label="本科" value="bachelor"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="graduatedFrom">
                <el-input
                  v-model="form.graduatedFrom"
                  placeholder="请输入毕业院校"
                  disabled
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="所学专业" prop="major">
                <el-input
                  v-model="form.major"
                  placeholder="请输入所学专业"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input
                  type="textarea"
                  :rows="3"
                  v-model="form.address"
                  placeholder="请输入详细地址"
                  disabled
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="邮编" prop="postCode">
                <el-input
                  v-model="form.postCode"
                  placeholder="请输入邮编"
                  disabled
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="传真" prop="fax">
                <el-input
                  v-model="form.fax"
                  placeholder="请输入传真"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="email">
                <el-input
                  v-model="form.email"
                  placeholder="请输入电子邮箱"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="工作简历" prop="workResume">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="form.workResume"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">单位信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位名称" prop="unitName">
                <el-input
                  v-model="form.unitName"
                  placeholder="请输入单位名称"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="单位统一信用代码"
                prop="socialCreditCode"
                label-width="150px"
              >
                <el-input
                  v-model="form.socialCreditCode"
                  placeholder="请输入统一信用代码"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属区域" prop="administrativeArea">
                <el-select
                  v-model="form.administrativeArea"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option
                    label="四川省-成都市-武侯区"
                    value="Sichuan-Chengdu-Wuhou"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="所在单位性质"
                prop="unitNature"
                label-width="150px"
              >
                <el-select
                  v-model="form.unitNature"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option label="企业" value="enterprise"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="联系人姓名"
                prop="contact"
                label-width="85px"
              >
                <el-input
                  v-model="form.contact"
                  placeholder="请输入联系人姓名"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="手机号码"
                prop="unitPhonenumber"
                label-width="150px"
              >
                <el-input
                  v-model="form.unitPhonenumber"
                  placeholder="请输入手机号码"
                  disabled
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <!-- 档案缺失情况 -->
          <el-divider content-position="left">档案缺失情况</el-divider>

          <el-form-item>
            <el-checkbox-group v-model="form.recordMissing" disabled>
              <el-checkbox label="全缺"></el-checkbox>
              <el-checkbox label="照片"></el-checkbox>
              <el-checkbox label="申请表"></el-checkbox>
              <el-checkbox label="身份证"></el-checkbox>
              <el-checkbox label="学历证明"></el-checkbox>
              <el-checkbox label="体检证明"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 协议缺失情况 -->
          <el-divider content-position="left">协议缺失情况</el-divider>

          <el-form-item>
            <el-checkbox v-model="form.agreementStatus" disabled
              >缺协议</el-checkbox
            >
          </el-form-item>

          <!-- 备注 -->
          <el-divider content-position="left">备注</el-divider>

          <el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              :rows="3"
              v-model="form.remarks"
              placeholder="请输入备注"
              disabled
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="cancelLook">关 闭</el-button>
        </div>
      </el-dialog>


      <file-upload-modal
      :visible="showUploadModal"
      :students="students"
      :businessId="registrationIdsUpload"
      :defaultMode="defaultMode"
      @update:visible="val => showUploadModal = val"
      @confirm="handleUploadConfirm"
      @close="handleModalClose"
    />


    <!-- 2. 档案上传确认组件 -->
    <FileUploadConfirmation
      :visible.sync="showFileConfirmation"
      :userData="studentInitialData"
      :registrationId="registrationId"
      dialog-title="员工档案上传确认"
      dialog-width="85%"
      @single-confirm="handleFileSubmit"
      @confirm="handleFileSubmit"
      @midway-confirm="handleMidwaySave"
      @close="closeAllModals"
    />


    <!-- 3. 操作结果提示 -->
    <el-dialog
      :visible.sync="showResultDialog"
      :title="resultSuccess ? '操作成功' : '操作失败'"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="result-content">
        <i class="el-icon-check-circle success-icon" v-if="resultSuccess"></i>
        <i class="el-icon-error-circle error-icon" v-else></i>
        <p>{{ resultMessage }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showResultDialog = false">确定</el-button>
      </div>
    </el-dialog>
    </el-col>
  </div>
</template>

<script>
import {
  listRegistration,
  getRegistration,
  delRegistration,
  addRegistration,
  updateRegistration,
  registrationList,
  addPerson,
  updateInfo,
  deleteInfo,
  addGroup,
  exportData,
} from "@/api/training/registration";
import {handleRecordsSubmit,selectRecordsByRegistrationIds} from "@/api/training/records";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { projectTreeSelect } from "@/api/training/projects";
import { getToken } from "@/utils/auth";
import FileUploadModal from "@/components/FileUpload/FileUploadModal.vue";
import FileUploadConfirmation from '@/components/FileUpload/FileUploadConfirmation.vue';
import {
  getRemarksByParams,
  listRemarksByParams,
} from "@/api/training/remarks";



export default {
  name: "Registration",
  components: { Treeselect, Splitpanes, Pane, FileUploadModal, FileUploadConfirmation },
  provide() {
    return {
      requestUpdate: () => {}, // 提供一个空函数作为默认实现
    };
  },
  data() {
    return {
      registrationId:"",
      //档案数量
      recordDto:null,
      fileLimit:6,
      // 模态框控制
      showUploadModal: false,
      showFileConfirmation: false,
      showResultDialog: false,


      // 结果信息
      resultSuccess: false,
      resultMessage: '',
      submitResult: null,


      // 上传配置
      defaultMode: "0", // 覆盖模式 (cover 0 / append 1)
      registrationIdsUpload: "", // 报名id

      // 学员列表数据
      students: null,


      // 学员初始档案数据（模拟从后端获取）
      studentInitialData: [{
              id:0,
              name:"",
              registrationId:"",
              urls: [],
              remark:"",
              fileTypes:[]
              }],


      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      registrationList: [],
      open: false,
      openLook: false,
      title: "",
      searchKey: "",
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        idNumber: null,
        certNumber: null,
        trainingType: null,
        phonenumber: null,
        unitName: null,
        paymentStatus: null,
        recordStatus: null,
        submitStatus: null,
        startTime: null,
        endTime: null,
        projectId: null, // 用于接收树节点选中值
      },
      //树形结构数据
      projectName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      //批量删除ids
      registrationIds: [],
      //上传
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      // 档案缺失情况的索引到标签映射
      archiveIndexToLabelMap: {
        0: "全缺",
        1: "照片",
        2: "申请表",
        3: "身份证",
        4: "学历证明",
        5: "体检证明",
      },
      // 标签到索引的映射
      archiveLabelToIndexMap: {
        全缺: 0,
        照片: 1,
        申请表: 2,
        身份证: 3,
        学历证明: 4,
        体检证明: 5,
      },
      //个人
      dialogVisible: false,
      form: {
        subjectId: "",
        trainingClass: "",
        trainingType: "新训",
        name: "",
        idType: "idCard",
        certificateStarttime: "", // 证件有效期开始时间
        certificateEndtime: "", // 证件有效期结束时间
        idValidDate: [], // 前端使用的日期范围数组
        gender: "男",
        nation: "",
        qualification: "",
        school: "",
        major: "",
        address: "",
        zipcode: "",
        fax: "",
        email: "",
        companyName: "",
        socialCreditCode: "",
        administrativeArea: "",
        unitNature: "enterprise",
        contact: "",
        phonenumber: "",
        archiveMissing: [],
        protocolMissing: false,
        remark: "",
        recordMissing: [],
        agreementStatus: false,
        workPeriod: [], // 工作时间
        workUnit: "", // 工作单位
        workResume: "请输入工作简历内容，可自由编辑", // 工作简历
      },

      addPersonRules: {
        projectId: [
          { required: true, message: "请选择报名项目", trigger: "change" },
        ],
        trainingType: [
          { required: true, message: "请选择培训类别", trigger: "change" },
        ],
        studentName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        phonenumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
        certificateType: [
          { required: true, message: "请输入证件类型", trigger: "blur" },
        ],
        idNumber: [
          { required: true, message: "请输入证件号码", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请输入性别", trigger: "blur" }],
        birthDate: [
          { required: true, message: "请输入出生年月", trigger: "blur" },
        ],
        qualification: [
          { required: true, message: "请输入学历", trigger: "blur" },
        ],
      },
      // 新增集体报名弹窗
      groupOpen: false,
      groupTitle: "新增集体报名",
      groupActiveTab: "unitInfo", // 当前激活的标签页
      groupForm: {
        unitName: "",
        socialCreditCode: "",
        administrativeArea: "",
        unitNature: "",
        contact: "",
        unitPhonenumber: "",
      },
      // 个人报名信息（用于集体报名中的个人列表）
      personForm: {
        subjectId: "",
        trainingClass: "",
        trainingType: "新训",
        studentName: "",
        phonenumber: "",
        certificateType: "idCard",
        idNumber: "",
        idValidDate: [],
        certificateStarttime: "",
        certificateEndtime: "",
        userType: "",
        sex: "男",
        birthDate: "",
        nation: "",
        qualification: "",
        school: "",
        major: "",
        address: "",
        postCode: "",
        fax: "",
        email: "",
        unitName: "",
        socialCreditCode: "",
        administrativeArea: "",
        unitNature: "",
        contact: "",
        unitPhonenumber: "",
        recordMissing: [],
        agreementStatus: false,
        remarks: "",
        workPeriod: [], // 工作时间
        workUnit: "", // 工作单位
        workResume: "请输入工作简历内容，可自由编辑", // 工作简历
      },
      // 存储已添加的个人用户列表
      personList: [],
      // 文件上传相关
      uploadUrl:
        process.env.VUE_APP_BASE_API + "/training/registration/importData",
      fileList: [],
      uploadSuccess: false,
      uploadedFileName: "",
      groupTitle: "新增集体报名", // 默认值
      //个人报名
      importOpen: false, // 控制导入弹窗显示
      importTitle: "导入个人报名信息",
      importForm: {
        uploadMode: "overwrite",
      },
      importRules: {
        uploadMode: [
          { required: true, message: "请选择上传方式", trigger: "change" },
        ],
      },
      // 文件上传相关
      importFileList: [],
      importSuccess: false,
      importedFileName: "",
      // 所有部门树选项
      projectOptions: undefined,
      remarkVisible: false, // 控制备注弹窗显示
      remarkTitle: "报名备注", // 弹窗标题
      remarkForm: {
        remarks: "", // 当前备注内容
        registrationId: null, // 关联的报名ID
      },
      remarkTempId: "", //备注弹窗  参数ID
      exportDataTempIds: [], //导出数据IDs
      remarkHistory: [
        {
          time: "2025-09-09 09:09:09",
          operator: "XXX",
          content: "需要补交材料",
        },
        {
          time: "2025-09-09 09:09:09",
          operator: "XXX",
          content: "已审核通过",
        },
      ],
      //提交申请表数据
      submitDialogTitle: "提交申请表",
      submitDialogVisible: false, // 控制提交申请表弹窗显示
      fileList: [], // 文件列表
      uploadedFileName: "", // 已上传文件名
      uploadSuccess: false, // 上传成功状态
      //必填规则限制
      groupRules: {
        // unitName: [
        //   { required: true, message: "请输入单位名称", trigger: "blur" },
        // ],
        socialCreditCode: [
          { required: true, message: "请输入统一信用代码", trigger: "blur" },
        ],
        administrativeArea: [
          { required: true, message: "请选择所属区域", trigger: "change" },
        ],
        unitNature: [
          { required: true, message: "请选择单位性质", trigger: "change" },
        ],
        contact: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
        ],
        unitPhonenumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getProjectTree();
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 打开提交申请表弹窗
    handleSubmit(row) {
      this.submitDialogVisible = true;
      this.fileList = [];
      this.uploadedFileName = "";
      this.uploadSuccess = false;

      // 如果有已上传的文件，可以在这里加载
      // this.loadExistingFile(row.id);
    },
    // 关闭提交申请表弹窗
    closeSubmitDialog() {
      this.submitDialogVisible = false;
      this.fileList = [];
      this.uploadedFileName = "";
      this.uploadSuccess = false;
    },

    // 处理文件上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.uploadSuccess = true;
        this.uploadedFileName = file.name;
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败：" + response.msg);
      }
    },

    // 提交申请表
    submitApplication() {
      if (!this.uploadSuccess) {
        this.$message.warning("请先上传申请表");
        return;
      }

      this.$confirm("确认提交该申请表吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用后端API提交申请表
          submitApplication({
            registrationId: this.currentRow.id,
            fileName: this.uploadedFileName,
          }).then((response) => {
            if (response.code === 200) {
              this.$message.success("提交成功");
              this.closeSubmitDialog();
              this.getList(); // 刷新列表
            } else {
              this.$message.error("提交失败：" + response.msg);
            }
          });
        })
        .catch(() => {});
    },

    // 取消提交
    cancelSubmit() {
      this.closeSubmitDialog();
    },

    // 加载已存在的文件（可选）
    loadExistingFile(registrationId) {
      // 这里应该调用后端API获取已上传的文件
      // 示例：getUploadedFile(registrationId).then(response => {
      //   if (response.data) {
      //     this.fileList = [response.data];
      //     this.uploadSuccess = true;
      //     this.uploadedFileName = response.data.name;
      //   }
      // });
    },

    // 备注弹窗
    handleRemark() {
      var remarkQuery = {
        foreignId: this.remarkTempId,
        remarkType: "1",
      };

      getRemarksByParams(remarkQuery).then((response) => {
        this.remarkForm.remarks = response.data.remarks || "";
      });

      var remarkListQuery = {
        foreignId: this.remarkTempId,
        remarkType: "1",
      };
      // 获取该报名的备注历史
      listRemarksByParams(remarkListQuery).then((response) => {
        // 将返回的数据赋值给remarkHistory，如果为空则使用默认值
        if (response.rows.length > 0) {
          // 根据实际返回的数据结构进行映射
          this.remarkHistory = response.rows.map((item) => {
            return {
              time: item.createTime || "",
              operator: item.createBy || "",
              content: item.remarks || item.content || "",
            };
          });
        } else {
          // 默认值
          this.remarkHistory = [
            {
              time: "2025-09-09 09:09:09",
              operator: "系统",
              content: "暂无备注记录",
            },
          ];
        }
      });

      this.remarkVisible = true;
    },

    // 重置备注表单
    resetRemarkForm() {
      this.$nextTick(() => {
        if (this.$refs.remarkForm) {
          this.$refs.remarkForm.resetFields();
        }
      });
    },

    // 提交备注
    submitRemark() {
      this.$refs["remarkForm"].validate((valid) => {
        if (valid) {
          // 调用后端API提交备注
          // 示例：addRemark(this.remarkForm).then(() => {
          //   this.$message.success("备注提交成功");
          //   this.remarkVisible = false;
          //   this.getList(); // 刷新列表
          // });

          // 模拟成功
          this.$message.success("备注提交成功");
          this.remarkVisible = false;
          this.getList(); // 刷新列表
        }
      });
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.projectId = data.id;
      // registrationList(this.queryParams);
      this.queryParams.pageNum = 1;
      this.getList(this.queryParams);
    },
    /** 下拉树结构 */
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
        // this.enabledProjectOptions = this.filterDisabledDept(
        //   JSON.parse(JSON.stringify(response.data))
        // );
      });
    },
    // 导入
    handleImport() {
      this.resetImportForm();
      this.importTitle = "导入报名信息";
      this.importOpen = true;
    },
    resetImportForm() {
      this.$refs["importForm"]?.resetFields();
      this.importFileList = [];
      this.importSuccess = false;
      this.importedFileName = "";
    },

    handleImportRemove(file, fileList) {
      this.importFileList = fileList;
      this.importSuccess = false;
      this.importedFileName = "";
    },

    // 档案缺失情况选择处理
    handleArchiveMissingChange(value) {
      // 如果选择了"全缺"，则选中所有选项
      if (value.includes("全缺")) {
        this.form.recordMissing = [
          "全缺",
          "照片",
          "申请表",
          "身份证",
          "学历证明",
          "体检证明",
        ];
      }
      // 如果取消了"全缺"选项
      else if (
        !value.includes("全缺") &&
        this.form.recordMissing.includes("全缺")
      ) {
        // 当取消"全缺"时，清空所有选项
        // this.form.recordMissing = [];
        this.form.recordMissing = "";
      }
      // 其他情况保持当前选择
      else {
        this.form.recordMissing = value;
      }
    },
    // 导出申请表
    handleExportTable() {

      var ids = [];
      this.exportDataTempIds.forEach((item) => {
        ids = String(item);
        console.log(ids);
      });

       this.$confirm("是否确认导出所有数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            return this.download(
              "/training/registration/export/applicationForm",
              {
                registrationIds : ids,
              },
              `registration_${new Date().getTime()}.docx`
            );
          })
          .catch(() => {});
    },

    /**
     * 处理FileUploadModal的确认事件
     * 上传完成后自动跳转到确认页面，并更新学员档案数据
     */
    getUrlsBySecondDir(query, fileList) {
    // 初始化结果数组
    const resultUrls = [];

    // 遍历文件列表
    fileList.forEach(file => {
        // 分割relativePath为目录数组（按"/"分割）
        const pathSegments = file.relativePath.split('/');
        // 校验路径格式（至少包含三级：一级/二级/文件名）
        if (pathSegments.length >= 3) {
            // 二级目录为数组的第1个索引（索引从0开始）
            const secondDir = pathSegments[1];
            // 精确匹配二级目录与查询字符串
            if (secondDir === query) {

                      // 匹配成功则添加url到结果数组
                      resultUrls.push(file.url);
                  }
              }
          })
          return resultUrls;
      },
    handleUploadConfirm(result) {
      console.log("文件上传完成，开始处理数据：", result);
      if(result.uploadMode === "1"){
          const targetStudents=result.targetStudents
          this.studentInitialData=targetStudents.map(item =>{
            let name =item.name
            let resultUrls =[]
            for(let i=0;i<this.students.length;i++){
              if(name === this.students[i].name){
                resultUrls = this.students[i].urls
              }
            }
            const Urls = this.getUrlsBySecondDir(name, result.fileDetails);
            console.log(Urls)
            const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(Urls);
            let emptyUrlCount = 0;
            if( fileLimit - Urls.length >=0){
              emptyUrlCount = fileLimit - Urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let remark="";
            let fileTypes=[];
            for(let i=0;i<this.students.length;i++){
              if(item.id === this.students[i].id){
                remark =this.students[i].remark
                fileTypes= this.students[i].fileTypes;
              }
            }

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypes.push("");
              }
            }

            return {
              id:item.id,
              name:name,
              registrationId:item.id,
              urls: finalUrls,
              remark:remark,
              fileTypes:fileTypes
              }
          })
          console.log(this.studentInitialData)
      }else{
        const targetStudents=result.targetStudents
          this.studentInitialData=targetStudents.map(item =>{
            let name =item.name
            let resultUrls =[]
            const Urls = this.getUrlsBySecondDir(name, result.fileDetails);
            const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(Urls);
            let emptyUrlCount = 0;
            if( fileLimit - Urls.length >=0){
              emptyUrlCount = fileLimit - Urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let remark="";
            let fileTypes=[];

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypes.push("");
              }
            }

            return {
              id:item.id,
              name:name,
              registrationId:item.id,
              urls: finalUrls,
              remark:remark,
              fileTypes:fileTypes
              }
          })
          console.log(this.studentInitialData)
      }

      // 关闭上传模态框
      this.showUploadModal = false;

      // 核心：更新学员档案数据（按姓名分组URL）
      this.updateStudentDataAfterUpload(result);

      // 显示确认页面
      this.showFileConfirmation = true;

      // 滚动到页面顶部
      window.scrollTo(0, 0);
    },


    /**
     * 处理FileUploadConfirmation的提交事件
     */
    handleFileSubmit(submitData) {
      console.log('档案信息提交，数据结构：', submitData);

      // 保存提交结果（调试用）
      this.submitResult = submitData;

      // 模拟API请求（实际项目替换为真实接口）
      handleRecordsSubmit(submitData).then((response) => {
        // 显示成功提示
        this.resultSuccess = true;
        this.resultMessage = "档案信息已成功保存至服务器";
        this.showResultDialog = true;

        // 关闭确认页面
        this.showFileConfirmation = false;
      });
    },
    handleMidwaySave(submitData) {
      console.log('中途保存数据（当前及之前用户）:', submitData);
      // 保存提交结果（调试用）
      this.submitResult = submitData;

      // 模拟API请求（实际项目替换为真实接口）
      handleRecordsSubmit(submitData).then((response) => {
        console.log(response.rows);
        // 显示成功提示
        this.resultSuccess = true;
        this.resultMessage = "档案信息已成功保存至服务器";
        this.showResultDialog = true;

        // 关闭确认页面
        this.showFileConfirmation = false;
      });
    },


    /**
     * 关闭所有模态框/组件
     */
    closeAllModals() {
      this.showUploadModal = false;
      this.showFileConfirmation = false;
    },


    /**
     * 处理上传模态框关闭事件
     */
    handleModalClose() {
      // console.log("上传模态框已手动关闭");
      this.showUploadModal = false;
    },


    /**
     * 核心方法：上传后更新学员档案数据（按姓名分组URL）
     * @param {Object} uploadResult - 上传结果数据（含fileDetails和relativePath）
     */
    updateStudentDataAfterUpload(uploadResult) {
      // 1. 校验上传结果有效性
      if (!uploadResult || !uploadResult.fileDetails || uploadResult.fileDetails.length === 0) {
        this.$message.warning("未获取到有效上传文件，学员档案未更新");
        return;
      }

      try {
        // 2. 按学员姓名分组URL（从relativePath提取姓名，新格式：test/学员姓名/文件名）
        const studentUrlMap = this.groupUrlsByStudentName(uploadResult.fileDetails);
        if (Object.keys(studentUrlMap).length === 0) {
          this.$message.warning("未从文件路径中提取到有效学员姓名，无法更新档案");
          return;
        }

        // 3. 根据分组结果更新对应学员的URLs
        this.updateStudentUrlsByGroup(studentUrlMap,uploadResult.uploadMode);

        // 4. 提示更新结果
        const updatedStudentCount = Object.keys(studentUrlMap).length;
        this.$message.success(`已成功更新${updatedStudentCount}名学员的档案，共新增${uploadResult.fileDetails.length}个文件`);

      } catch (error) {
        // console.error("更新学员档案时发生错误：", error);
        this.$message.error(`档案更新失败：${error.message || '未知错误'}`);
      }
    },


    /**
 * 辅助方法1：从fileDetails中按学员姓名分组URL（核心：解析relativePath）
 * @param {Array} fileDetails - 上传文件详情数组（含relativePath和url）
 * @returns {Object} 学员姓名→URL数组的映射（格式：{ "张三": [url1, url2] }）
 * @description 适配三层路径格式：任意前缀/学员姓名/文件名.后缀
 */
  groupUrlsByStudentName(fileDetails) {
    const studentUrlMap = {};

    fileDetails.forEach((file, index) => {
      // 1. 基础校验：文件详情必须包含relativePath和url
      if (!file.relativePath || !file.url) {
        // console.warn(`第${index + 1}个文件信息不完整（缺少路径或URL），跳过处理`);
        return;
      }

      // 2. 解析路径：按"/"分割，过滤空片段（处理前后斜杠导致的空值）
      const pathSegments = file.relativePath.split("/")
        .filter(segment => segment.trim() !== "");

      // 3. 格式校验：必须满足三层结构 "任意前缀/学员姓名/文件名" → 至少3个有效片段
      if (pathSegments.length < 3) {
        // console.warn(`第${index + 1}个文件路径格式错误（应为"任意前缀/学员姓名/文件名"）：${file.relativePath}，跳过处理`);
        return;
      }

      // 4. 提取学员姓名：第2个有效片段（索引1，三层结构中固定为学员姓名位置）
      const studentName = pathSegments[1].trim()
        .replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ""); // 只保留中文、字母、数字

      // 5. 姓名有效性校验
      if (!studentName) {
        // console.warn(`第${index + 1}个文件路径中未提取到有效学员姓名：${file.relativePath}，跳过处理`);
        return;
      }

      // 6. 分组URL（去重，避免重复添加同一文件）
      if (!studentUrlMap[studentName]) {
        studentUrlMap[studentName] = [];
      }
      if (!studentUrlMap[studentName].includes(file.url)) {
        studentUrlMap[studentName].push(file.url);
        // console.log(`文件关联成功：学员「${studentName}」→ 文件名「${file.name}」→ URL「${file.url}」`);
      } else {
        // console.log(`文件已存在：学员「${studentName}」的「${file.name}」无需重复添加`);
      }
    });

    return studentUrlMap;
  },


    /**
     * 辅助方法2：根据姓名分组结果，更新studentInitialData对应学员的URLs
     * @param {Object} studentUrlMap - 学员姓名→URL数组的映射
     */
    updateStudentUrlsByGroup(studentUrlMap,uploadMode) {
      this.studentInitialData.forEach((student, studentIndex) => {
        // 找到当前学员在分组中的新URL列表
        const newUrls = studentUrlMap[student.name] || [];
        if (newUrls.length === 0) return; // 无对应新URL，跳过当前学员

        // 1. 保留学员原有非空URL（避免覆盖已存在的有效档案）
        const existingValidUrls = student.urls.filter(url => url && url.trim() !== "");
        console.log(`学员「${student.name}」原有有效档案数：${existingValidUrls.length}个`);

        // 2. 合并原有URL和新URL（去重处理）
        const mergedUrls = [...new Set([...existingValidUrls, ...newUrls])];
        console.log(`学员「${student.name}」合并后总档案数：${mergedUrls.length}个`);

        // 3. 按规则限制文件数量
        const fileLimit = this.fileLimit; // 所有学员最多6个文件
        const finalUrls = mergedUrls.slice(0, fileLimit); // 超过限制时截取前N个

        // 4. 补充空URL至限制数量（保持界面显示一致，空URL对应"点击上传"提示）
        const emptyUrlCount = fileLimit - finalUrls.length;
        for (let i = 0; i < emptyUrlCount; i++) {
          finalUrls.push("");
        }

        // 5. 响应式更新学员URLs（必须用$set确保Vue检测到数组变化）
        this.$set(student, "urls", finalUrls);
        // console.log(uploadMode)
        // if(uploadMode === "1"){
        //   console.log(student.urls)
        //   const mergedUrls = [...new Set([...student.urls, ...newUrls])];student.urls
        //   console.log(mergedUrls)
        //   this.$set(student, "urls", mergedUrls);
        // }else{
        //   console.log(newUrls)
        //   this.$set(student, "urls", newUrls);
        // }

        // 6. 日志提示最终结果
        const addedCount = mergedUrls.length - existingValidUrls.length;
        // console.log(
        //   `学员「${student.name}」档案更新完成：新增${addedCount}个，当前共${finalUrls.filter(url => url).length}个有效档案（限制${fileLimit}个）`
        // );
      });
    },

    /**
     * 刷新学员数据（从后端获取最新数据，实际项目使用）
     */
    refreshStudentData() {
      this.$message.info('正在从服务器刷新最新档案数据...');

      // 模拟API请求（实际项目替换为真实接口）
      setTimeout(() => {
        // 响应式更新学员初始数据
        // this.studentInitialData = mockNewData;
        this.$message.success('档案数据已刷新，与服务器保持同步');
      }, 1000);
    },
    async handleExportTest1() {
      this.registrationIdsUpload = this.ids.join(',');
      if(this.ids.length !=0 ){
        this.registrationId =this.recordDto[0].registrationId
      }
      const response = await selectRecordsByRegistrationIds(this.registrationIdsUpload);
      this.students=response.map(item =>{
          const recordsList=item.recordsList
          let fileTypes=[]
          let urls=[]
          for(let i=0;i<recordsList.length;i++){
            fileTypes.push(recordsList[i].recordType)
            urls.push(recordsList[i].url)
          }
          return {
            id:item.registrationId,
            name:item.studentName,
            requirements: ["身份证", "报名表"],
            remark:item.remark,
            fileTypes:fileTypes,
            urls:urls
          }
        })
      this.showUploadModal=true
    },
    async handleExportTest2() {
      this.registrationIdsUpload = this.ids.join(',');
      if(this.ids.length !=0 ){
        this.registrationId =this.recordDto[0].registrationId
      }
      const response=await selectRecordsByRegistrationIds(this.registrationIdsUpload)
      this.students=response.map(item =>{
          const recordsList=item.recordsList
          let fileTypes=[]
          let urls=[]
          for(let i=0;i<recordsList.length;i++){
            fileTypes.push(recordsList[i].recordType)
            urls.push(recordsList[i].url)
          }

          //补充
          let resultUrls =[]
          let resultFileTypes =[]
          const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(urls);
            let emptyUrlCount = 0;
            if( fileLimit - urls.length >=0){
              emptyUrlCount = fileLimit - urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let fileTypesFinal=resultFileTypes.concat(fileTypes);

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypesFinal.push("");
              }
            }
          return {
            id:item.registrationId,
            name:item.studentName,
            requirements: ["身份证", "报名表"],
            remark:item.remark,
            fileTypes:fileTypesFinal,
            urls:finalUrls
          }
        })
        this.studentInitialData=this.students.map(item =>{
            return {
              id:item.id,
              name:item.name,
              registrationId:item.id,
              urls: item.urls,
              remark:item.remark,
              fileTypes:item.fileTypes
              }
          })
      this.showFileConfirmation=true
    },

    // 新增个人报名
    handleAddPersonal() {
      this.resetForm();
      // 确保表单数据完全清空
      this.dialogVisible = true;
    },
    resetForm() {
      // 安全地调用 resetFields，确保引用存在
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("提交数据:", this.form);
          // 这里可以调用 API 提交数据
          this.dialogVisible = false;
        } else {
          console.log("表单校验失败");
        }
      });
    },
    // 新增集体报名
    handleAddGroup() {
      this.resetGroupForm();
      this.groupOpen = true;
      this.groupStep = 1; // 重置步骤
    },
    // 重置集体报名表单
    resetGroupForm() {
      this.$refs["groupForm"]?.resetFields();
      this.$refs["personForm"]?.resetFields();
      this.groupForm = {
        unitName: "",
        creditCode: "",
        region: "",
        unitType: "",
        contactName: "",
        phone: "",
      };
      this.personForm = {
        subjectId: "",
        trainingClass: "",
        trainingType: "新训",
        studentName: "",
        phonenumber: "",
        certificateType: "idCard",
        idNumber: "",
        idValidDate: [],
        certificateStarttime: "",
        certificateEndtime: "",
        userType: "",
        sex: "男",
        birthDate: "",
        nation: "",
        qualification: "",
        school: "",
        major: "",
        address: "",
        postCode: "",
        fax: "",
        email: "",
        unitName: "",
        socialCreditCode: "",
        administrativeArea: "",
        unitNature: "",
        contact: "",
        unitPhonenumber: "",
        recordMissing: [],
        agreementStatus: false,
        remarks: "",
        workPeriod: [], // 工作时间
        workUnit: "", // 工作单位
        workResume: "请输入工作简历内容，可自由编辑", // 工作简历
      };
      this.personList = [];
      this.groupActiveTab = "unitInfo"; // 重置到第一个标签页
      this.groupTitle = "新增集体报名";
    },
    // 下一步（从单位信息到个人信息）
    nextStep() {
      this.$refs["groupForm"].validate((valid) => {
        if (valid) {
          this.groupActiveTab = "personInfo";
          this.groupTitle = "新增集体报名 - 人员信息";
        }
      });
    }, // 上一步（从个人信息回到单位信息）
    prevStep() {
      this.groupActiveTab = "unitInfo";
      this.groupTitle = "新增集体报名";
    },
    // 继续添加（保存当前个人信息并清空表单）
    continueAddPerson() {
      this.$refs["personForm"].validate((valid) => {
        if (valid) {
          // 处理证件有效期字段转换
          if (
            Array.isArray(this.personForm.idValidDate) &&
            this.personForm.idValidDate.length === 2
          ) {
            this.personForm.certificateStarttime =
              this.personForm.idValidDate[0];
            this.personForm.certificateEndtime = this.personForm.idValidDate[1];
          } else {
            this.personForm.certificateStarttime = "";
            this.personForm.certificateEndtime = "";
          }

          // 保存当前个人信息到列表
          this.personList.push({ ...this.personForm });

          // 清空个人信息表单（保留部分单位信息）
          this.personForm.studentName = "";
          this.personForm.phonenumber = "";
          this.personForm.idNumber = "";
          this.personForm.idValidDate = [];
          this.personForm.certificateStarttime = "";
          this.personForm.certificateEndtime = "";
          this.personForm.workPeriod = []; // 清空工作时间
          this.personForm.workResume = ""; // 清空工作简历
          this.personForm.workResume = "请输入工作简历内容，可自由编辑"; // 清空工作简历
          // 保留其他字段或根据需要重置

          this.$message.success("人员信息已保存，可继续添加");
        }
      });
    },
    // 添加工作经历到简历中
    addWorkExperience() {
      const workPeriod = this.personForm.workPeriod;
      const workUnit = this.personForm.workUnit;

      if (Array.isArray(workPeriod) && workPeriod.length === 2 && workUnit) {
        const start = workPeriod[0];
        const end = workPeriod[1];
        const newExperience = `${start}至${end}，在${workUnit}从事特种设备安全管理工作`;

        if (this.personForm.workResume) {
          // 如果已有简历内容，追加新内容
          this.personForm.workResume += `\n${newExperience}`;
        } else {
          // 如果没有简历内容，直接设置
          this.personForm.workResume = newExperience;
        }

        // 清空当前输入，为下一次输入做准备
        this.personForm.workPeriod = [];
        this.personForm.workUnit = "";
      } else {
        this.$message.warning("请完整填写工作时间和工作单位");
      }
    },
    addPersonWorkExperience() {
      const workPeriod = this.form.workPeriod;
      const workUnit = this.form.workUnit;

      if (Array.isArray(workPeriod) && workPeriod.length === 2 && workUnit) {
        const start = workPeriod[0];
        const end = workPeriod[1];
        const newExperience = `${start}至${end}，在${workUnit}从事特种设备安全管理工作`;

        if (this.form.workResume) {
          // 如果已有简历内容，追加新内容
          this.form.workResume += `\n${newExperience}`;
        } else {
          // 如果没有简历内容，直接设置
          this.form.workResume = newExperience;
        }

        // 清空当前输入，为下一次输入做准备
        this.form.workPeriod = [];
        this.form.workUnit = "";
      } else {
        this.$message.warning("请完整填写工作时间和工作单位");
      }
    },
    // 完成集体报名（提交数据）
    finishGroupRegistration() {
      // 如果当前在已添加人员标签页，直接提交数据
      if (this.groupActiveTab === "addedPersons") {
        this.submitGroupData();
        return;
      }

      // 验证当前标签页的表单
      const currentFormRef =
        this.groupActiveTab === "personInfo" ? "personForm" : "groupForm";

      this.$refs[currentFormRef].validate((valid) => {
        if (valid) {
          // 如果在人员信息标签页且有填写信息，则保存最后一个人
          if (this.groupActiveTab === "personInfo") {
            // 检查是否填写了必要信息
            if (
              this.personForm.studentName ||
              this.personForm.phonenumber ||
              this.personForm.idNumber
            ) {
              // 处理证件有效期字段转换
              if (
                Array.isArray(this.personForm.idValidDate) &&
                this.personForm.idValidDate.length === 2
              ) {
                this.personForm.certificateStarttime =
                  this.personForm.idValidDate[0];
                this.personForm.certificateEndtime =
                  this.personForm.idValidDate[1];
              } else {
                this.personForm.certificateStarttime = "";
                this.personForm.certificateEndtime = "";
              }

              // 处理档案缺失情况字段转换
              if (
                Array.isArray(this.personForm.recordMissing) &&
                this.personForm.recordMissing.length > 0
              ) {
                const indices = this.personForm.recordMissing
                  .map((label) => this.archiveLabelToIndexMap[label])
                  .filter((index) => index !== undefined);
                this.personForm.recordMissing = indices.join(",");
              } else {
                this.personForm.recordMissing = "";
              }
              // 组装工作简历
              const workPeriod = Array.isArray(this.personForm.workPeriod)
                ? this.personForm.workPeriod
                : [];
              const workUnit = this.personForm.workUnit || "";

              if (workPeriod.length >= 2 && workUnit) {
                this.personForm.workResume = `${workPeriod[0]}至${workPeriod[1]}，在${workUnit}从事特种设备安全管理工作`;
              } else {
                this.personForm.workResume = "暂无工作经历"; // 或者设置默认值
              }
              // 将当前人员信息添加到列表
              this.personList.push({ ...this.personForm });
            }
          }
          // 提交数据
          this.submitGroupData();
        }
      });
    },

    // 提交集体报名数据到后端
    submitGroupData() {
      // 检查是否有人员信息
      if (this.personList.length === 0) {
        this.$message.warning("请至少添加一名人员信息");
        return;
      }

      // 构造提交数据
      const submitData = {
        unitInfo: {
          unitName: this.groupForm.unitName,
          creditCode: this.groupForm.creditCode,
          region: this.groupForm.region,
          unitType: this.groupForm.unitType,
          contactName: this.groupForm.contactName,
          phone: this.groupForm.phone,
        },
        personList: this.personList.map((person) => {
          // 处理档案缺失情况字段转换
          let processedRecordMissing = "";
          if (
            Array.isArray(person.recordMissing) &&
            person.recordMissing.length > 0
          ) {
            // 如果选择了"全缺"，则选中所有选项
            if (person.recordMissing.includes("全缺")) {
              processedRecordMissing = [
                "全缺",
                "照片",
                "申请表",
                "身份证",
                "学历证明",
                "体检证明",
              ].join(",");
            } else {
              const indices = person.recordMissing
                .map((label) => this.archiveLabelToIndexMap[label])
                .filter((index) => index !== undefined);
              processedRecordMissing = indices.join(",");
            }
          }

          return {
            subjectId: person.subjectId,
            projectId: person.projectId,
            trainingClass: person.trainingClass,
            trainingType: person.trainingType,
            studentName: person.studentName,
            phonenumber: person.phonenumber,
            certificateType: person.certificateType,
            idNumber: person.idNumber,
            certificateStarttime: person.certificateStarttime,
            certificateEndtime: person.certificateEndtime,
            userType: person.userType,
            sex: person.sex,
            birthDate: person.birthDate,
            nation: person.nation,
            qualification: person.qualification,
            school: person.school,
            major: person.major,
            address: person.address,
            postCode: person.postCode,
            fax: person.fax,
            email: person.email,
            unitName: person.unitName,
            socialCreditCode: person.socialCreditCode,
            administrativeArea: person.administrativeArea,
            unitNature: person.unitNature,
            contact: person.contact,
            unitPhonenumber: person.unitPhonenumber,
            recordMissing: processedRecordMissing, // 使用处理后的值
            agreementStatus: person.agreementStatus,
            remarks: person.remarks,
            workPeriod: person.workPeriod,
            workResume: person.workResume,
          };
        }),
      };

      console.log("提交集体报名数据:", submitData);

      addGroup(submitData).then((response) => {
        if (response.code === 200) {
          this.$message.success("集体报名成功");
          this.groupOpen = false;
          this.resetGroupForm(); // 重置表单
          this.getList(); // 刷新列表
        } else {
          this.$message.error("集体报名失败: " + response.msg);
        }
      });
    },
    removePerson(index) {
      this.personList.splice(index, 1);
    },
    // 下载模板
    downloadTemplate() {
      const link = document.createElement("a");
      link.href = "/template/Excel.xlsx"; // 模板文件路径
      link.download = "报名信息模板.xlsx"; // 下载后的文件名
      link.click();
    },

    // 文件上传成功回调
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.uploadSuccess = true;
        this.uploadedFileName = file.name;
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败：" + response.msg);
      }
    },

    // 文件上传前校验
    beforeUpload(file) {
      const validTypes = [
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ];
      if (!validTypes.includes(file.type)) {
        this.$message.error("只能上传 Excel 文件");
        return false;
      }
      return true;
    },

    // 删除已上传文件
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.uploadSuccess = false;
      this.uploadedFileName = "";
    },

    // 提交导入
    submitGroupImport() {
      this.$refs["groupForm"].validate((valid) => {
        if (valid && this.fileList.length > 0) {
          this.$confirm("确认导入该批次报名信息吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            // 模拟提交到后端
            const formData = new FormData();
            formData.append("unitInfo", JSON.stringify(this.groupForm));
            formData.append("file", this.fileList[0].raw);

            // 发送请求
            importRegistration(formData).then((response) => {
              if (response.code === 200) {
                this.$message.success("导入成功");
                this.groupOpen = false;
                this.getList(); // 刷新列表
              } else {
                this.$message.error("导入失败：" + response.msg);
              }
            });
          });
        } else {
          this.$message.warning("请填写完整信息并上传文件");
        }
      });
    },

    // 关闭弹窗
    cancelGroup() {
      this.groupOpen = false;
      this.resetGroupForm();
    },
    // 缴费二维码
    handleQRCode() {
      this.$message.info("生成缴费二维码");
    },

    // 转账缴费
    handleTransfer() {
      this.$message.info("进入转账缴费页面");
    },

    // 隐藏搜索
    toggleSearch() {
      this.$message.info("隐藏搜索区域");
    },

    // 刷新
    handleRefresh() {
      this.getList();
    },

    // 隐藏/排序列
    toggleColumns() {
      this.$message.info("切换列显示与排序");
    },
    // 删除
    handleDelete(row) {
      this.$modal.confirm("是否确认删除？").then(() => {
        deleteInfo(row.registrationId).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    // 多选框选中数据   多项数据id
    handleSelectionChange(selection) {
      this.recordDto=selection
      //传给备注弹窗的id
      this.remarkTempId =
        selection.length === 1 ? selection[0].registrationId : null;

      console.log(selection);
      this.exportDataTempIds = selection.map((item) => item.registrationId);
      console.log(this.exportDataTempIds);

      this.ids = selection.map((item) => item.registrationId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;

      //批量删除使用ids
      this.registrationIds = selection.map((item) => item.registrationId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 批量删除
    handleBatchDelete(row) {
      const registrationIds = row.registrationId || this.registrationIds;
      console.log("批量删除：", registrationIds);
      this.$modal
        .confirm('是否确认删除用户编号为"' + registrationIds + '"的数据项？')
        .then(function () {
          return deleteInfo(registrationIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 查询列表
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      if (this.dateRange && this.dateRange.length === 2) {
        params.startTime = this.dateRange[0];
        params.endTime = this.dateRange[1];
      }
      registrationList(params).then((response) => {
        this.registrationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置查询
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.searchKey = "";
      this.$refs.tree.filter("");
      // 重置树节点选择  projectId参数
      this.queryParams.projectId = null;
      // 清除树节点的当前高亮选中
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },

    // 新增
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报名";
    },

    // 修改
    handleUpdate(row) {
      this.reset();
      getRegistration(row.id).then((response) => {
        this.form = response.data;

        // 将后端的两个日期字段转换为前端使用的数组
        if (this.form.certificateStarttime && this.form.certificateEndtime) {
          this.form.idValidDate = [
            this.form.certificateStarttime,
            this.form.certificateEndtime,
          ];
        } else {
          this.form.idValidDate = [];
        }

        this.open = true;
        this.title = "修改报名";
      });
    },

    // 查看
    handleView(row) {
      this.reset(); // 重置表单

      if (row) {
        // 从表格行调用，查看特定行的数据
        getRegistration(row.registrationId)
          .then((response) => {
            this.form = response.data;

            // 处理日期字段转换
            if (
              this.form.certificateStarttime &&
              this.form.certificateEndtime
            ) {
              this.form.idValidDate = [
                this.form.certificateStarttime,
                this.form.certificateEndtime,
              ];
            } else {
              this.form.idValidDate = [];
            }

            // 处理档案缺失情况字段回显
            if (
              this.form.recordMissing &&
              typeof this.form.recordMissing === "string"
            ) {
              const indices = this.form.recordMissing
                .split(",")
                .map((item) => parseInt(item.trim()));
              this.form.recordMissing = indices
                .map((index) => this.archiveIndexToLabelMap[index])
                .filter((label) => label !== undefined);
            } else if (Array.isArray(this.form.recordMissing)) {
              // 如果已经是数组格式，保持不变
              this.form.recordMissing = [...this.form.recordMissing];
            } else {
              this.form.recordMissing = [];
            }
            // 处理协议缺失情况字段回显
            // 确保 agreementStatus 是布尔值
            if (typeof this.form.agreementStatus === "string") {
              this.form.agreementStatus =
                this.form.agreementStatus === "true" ||
                this.form.agreementStatus === "1";
            } else if (typeof this.form.agreementStatus === "number") {
              this.form.agreementStatus = this.form.agreementStatus === 1;
            } else if (typeof this.form.agreementStatus !== "boolean") {
              this.form.agreementStatus = !!this.form.agreementStatus;
            }

            this.openLook = true;
            this.title = "查看报名";
          })
          .catch((error) => {
            this.$message.error("获取数据失败: " + error.message);
          });
      } else {
        // 从操作栏调用，需要先选择一条数据
        if (this.ids.length === 1) {
          // 如果只选择了一条数据，则查看该数据
          const selectedId = this.ids[0];
          // 在实际应用中，你可能需要根据选中的ID获取数据
          // 这里假设 registrationList 中可以找到对应的数据
          const selectedRow = this.registrationList.find(
            (item) => item.registrationId === selectedId
          );
          if (selectedRow) {
            this.handleView(selectedRow);
          } else {
            // 如果在当前列表中找不到，则通过API获取
            getRegistration(selectedId)
              .then((response) => {
                this.form = response.data;

                // 处理日期字段转换
                if (
                  this.form.certificateStarttime &&
                  this.form.certificateEndtime
                ) {
                  this.form.idValidDate = [
                    this.form.certificateStarttime,
                    this.form.certificateEndtime,
                  ];
                } else {
                  this.form.idValidDate = [];
                }

                this.openLook = true;
                this.title = "查看报名";
              })
              .catch((error) => {
                this.$message.error("获取数据失败: " + error.message);
              });
          }
        } else if (this.ids.length > 1) {
          this.$message.warning("只能选择一条数据进行查看");
        } else {
          this.$message.warning("请先选择一条数据进行查看");
        }
      }
    },
    // 新增个人报名表单
    submitPersonForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 创建提交数据副本
          let submitForm = { ...this.form };

          // 处理档案缺失情况字段转换
          if (
            Array.isArray(this.form.recordMissing) &&
            this.form.recordMissing.length > 0
          ) {
            const indices = this.form.recordMissing
              .map((label) => this.archiveLabelToIndexMap[label])
              .filter((index) => index !== undefined);
            submitForm.recordMissing = indices.join(",");
          } else {
            submitForm.recordMissing = "";
          }
          console.log("提交数据:", typeof submitForm.recordMissing);
          // 处理证件有效期字段转换
          if (
            Array.isArray(this.form.idValidDate) &&
            this.form.idValidDate.length === 2
          ) {
            submitForm.certificateStarttime = this.form.idValidDate[0];
            submitForm.certificateEndtime = this.form.idValidDate[1];
          } else {
            submitForm.certificateStarttime = "";
            submitForm.certificateEndtime = "";
          }

          // 移除前端使用的 idValidDate 字段
          delete submitForm.idValidDate;

          // 调用API提交数据
          addPerson(submitForm)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("新增成功");
                this.dialogVisible = false;
                this.getList(); // 刷新列表
              } else {
                this.$message.error("新增失败: " + response.msg);
              }
            })
            .catch((error) => {
              this.$message.error("新增失败: " + error.message);
            });
        } else {
          this.$message.warning("请填写必填项");
          return false;
        }
      });
    },

    flattenProjectOptions(options, result = [], prefix = "") {
      if (!options || !Array.isArray(options)) return result;

      options.forEach((item) => {
        // 添加当前节点到结果中
        result.push({
          id: item.id,
          label: prefix + item.label,
          disabled: item.disabled,
        });

        // 递归处理子节点，添加层级前缀
        if (item.children && item.children.length > 0) {
          this.flattenProjectOptions(item.children, result, prefix + "　"); // 使用全角空格作为前缀
        }
      });

      return result;
    },

    // 获取扁平化的项目选项用于下拉框
    getFlattenedProjectOptions() {
      return this.flattenProjectOptions(this.projectOptions);
    },

    // 修改按钮
    handleEdit(row) {
      this.resetForm(); // 先清空表单
      this.open = true;

      if (row) {
        // 从表格行调用，编辑特定行的数据
        getRegistration(row.registrationId)
          .then((response) => {
            this.form = response.data;
            // 处理日期字段转换
            if (
              this.form.certificateStarttime &&
              this.form.certificateEndtime
            ) {
              this.form.idValidDate = [
                this.form.certificateStarttime,
                this.form.certificateEndtime,
              ];
            } else {
              this.form.idValidDate = [];
            }

            // 处理项目选择字段
            if (this.form.subjectId) {
              this.form.projectId = this.form.subjectId;
            }

            // 处理档案缺失情况字段回显
            if (
              this.form.recordMissing &&
              typeof this.form.recordMissing === "string"
            ) {
              const indices = this.form.recordMissing
                .split(",")
                .map((item) => parseInt(item.trim()));
              this.form.recordMissing = indices
                .map((index) => this.archiveIndexToLabelMap[index])
                .filter((label) => label !== undefined);
            } else if (Array.isArray(this.form.recordMissing)) {
              // 如果已经是数组格式，保持不变
              this.form.recordMissing = [...this.form.recordMissing];
            } else {
              this.form.recordMissing = [];
            }

            // 处理协议缺失情况字段回显
            // 确保 agreementStatus 是布尔值
            if (typeof this.form.agreementStatus === "string") {
              this.form.agreementStatus =
                this.form.agreementStatus === "true" ||
                this.form.agreementStatus === "1";
            } else if (typeof this.form.agreementStatus === "number") {
              this.form.agreementStatus = this.form.agreementStatus === 1;
            } else if (typeof this.form.agreementStatus !== "boolean") {
              this.form.agreementStatus = !!this.form.agreementStatus;
            }

            this.open = true;
            this.title = "修改报名";
          })
          .catch((error) => {
            this.$message.error("获取数据失败: " + error.message);
          });
      } else {
        // 从操作栏调用，需要先选择一条数据
        if (this.ids.length === 1) {
          // 如果只选择了一条数据，则编辑该数据
          const selectedId = this.ids[0];
          const selectedRow = this.registrationList.find(
            (item) => item.registrationId === selectedId
          );
          if (selectedRow) {
            this.handleEdit(selectedRow);
          } else {
            // 如果在当前列表中找不到，则通过API获取
            getRegistration(selectedId)
              .then((response) => {
                this.form = response.data;

                // 处理日期字段转换
                if (
                  this.form.certificateStarttime &&
                  this.form.certificateEndtime
                ) {
                  this.form.idValidDate = [
                    this.form.certificateStarttime,
                    this.form.certificateEndtime,
                  ];
                } else {
                  this.form.idValidDate = [];
                }

                // 处理项目选择字段
                if (this.form.subjectId) {
                  this.form.projectId = this.form.subjectId;
                }

                this.open = true;
                this.title = "修改报名";
              })
              .catch((error) => {
                this.$message.error("获取数据失败: " + error.message);
              });
          }
        } else if (this.ids.length > 1) {
          this.$message.warning("只能选择一条数据进行修改");
        } else {
          this.$message.warning("请先选择一条数据进行修改");
        }
      }
    },
    // 修改报名表单提交
    submitEditForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 创建提交数据副本
          let submitForm = { ...this.form };

          // 处理证件有效期字段转换
          if (
            Array.isArray(this.form.idValidDate) &&
            this.form.idValidDate.length === 2
          ) {
            submitForm.certificateStarttime = this.form.idValidDate[0];
            submitForm.certificateEndtime = this.form.idValidDate[1];
          } else {
            submitForm.certificateStarttime = "";
            submitForm.certificateEndtime = "";
          }

          // 处理档案缺失情况字段转换
          if (
            Array.isArray(this.form.recordMissing) &&
            this.form.recordMissing.length > 0
          ) {
            const indices = this.form.recordMissing
              .map((label) => this.archiveLabelToIndexMap[label])
              .filter((index) => index !== undefined);
            submitForm.recordMissing = indices.join(",");
          } else {
            submitForm.recordMissing = "";
          }

          // 处理档案缺失情况字段转换
          if (
            Array.isArray(this.form.recordMissing) &&
            this.form.recordMissing.length > 0
          ) {
            const indices = this.form.recordMissing
              .map((label) => this.archiveLabelToIndexMap[label])
              .filter((index) => index !== undefined);
            submitForm.recordMissing = indices.join(",");
          } else {
            submitForm.recordMissing = "";
          }
          console.log("提交数据:", submitForm.agreementStatus);
          // 移除前端使用的 idValidDate 字段
          delete submitForm.idValidDate;

          //修改
          updateInfo(submitForm)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("修改成功");
                // this.dialogVisible = false;
                this.open = false;
                this.getList(); // 刷新列表
              } else {
                this.$message.error("修改失败: " + response.msg);
              }
            })
            .catch((error) => {});
        } else {
          this.$message.warning("请填写必填项");
          return false;
        }
      });
    },
    // 集体报名上传相关方法
    getToken() {
      return getToken();
    },
    handleGroupUploadProgress(event, file, fileList) {
      this.uploadSuccess = true;
    },

    handleGroupUploadSuccess(response, file, fileList) {
      this.uploadSuccess = true;
      this.uploadedFileName = file.name;
      this.$message.success("上传成功");
    },

    handleGroupUploadError(err, file, fileList) {
      this.uploadSuccess = false;
      this.$message.error("上传失败");
    },

    submitGroupImport() {
      this.$refs["groupForm"].validate((valid) => {
        if (valid && this.fileList.length > 0) {
          this.$confirm("确认导入该批次报名信息吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            // 提交上传
            this.$refs.groupUpload.submit();

            // 处理表单数据
            const formData = new FormData();
            formData.append("unitInfo", JSON.stringify(this.groupForm));
            // 文件已经在上传时处理了

            importRegistration(formData).then((response) => {
              if (response.code === 200) {
                this.$message.success("导入成功");
                this.groupOpen = false;
                this.getList(); // 刷新列表
              } else {
                this.$message.error("导入失败：" + response.msg);
              }
            });
          });
        } else {
          this.$message.warning("请填写完整信息并上传文件");
        }
      });
    },

    //导入
    submitImport() {
      const file = this.$refs.upload.uploadFiles;
      if (
        !file ||
        file.length === 0 ||
        (!file[0].name.toLowerCase().endsWith(".xls") &&
          !file[0].name.toLowerCase().endsWith(".xlsx"))
      ) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。");
        return;
      }
      this.$refs.upload.submit();
    },
    cancelImport() {
      this.importOpen = false;
      this.resetImportForm();
    },

    handleExport() {
      this.$confirm("是否确认导出所有数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return this.download(
            "/training/registration/export",
            {
              ...this.queryParams,
            },
            `registration_${new Date().getTime()}.xlsx`
          );
        })
        .catch(() => {});
    },
    // 导出报名表（单行数据）
    handleExportForm(row) {
      this.$confirm('是否确认导出"' + row.name + '"的报名表？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用导出接口，传入具体记录的ID
          this.download(
            "/training/registration/exportById",
            {
              id: row.id,
            },
            `报名表_${row.name}_${new Date().getTime()}.xlsx`
          );
        })
        .catch(() => {});
    },

    // 提交表单
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updateRegistration(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegistration(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 取消
    cancel() {
      this.open = false;
      this.reset();
    },
    //查看弹框取消
    cancelLook() {
      this.openLook = false;
      this.reset();
    },
    resetForm() {
      this.form = {
        subjectId: "",
        trainingClass: "",
        trainingType: "新训",
        studentName: "",
        phonenumber: "",
        certificateType: "idCard",
        idNumber: "",
        idValidDate: [],
        sex: "男",
        birthDate: "",
        nation: "Han",
        position: "",
        qualification: "bachelor",
        graduatedFrom: "",
        major: "",
        address: "",
        postCode: "",
        fax: "",
        email: "",
        unitName: "",
        socialCreditCode: "",
        administrativeArea: "Sichuan-Chengdu-Wuhou",
        unitNature: "enterprise",
        contact: "",
        unitPhonenumber: "",
        recordMissing: [],
        agreementStatus: false,
        remarks: "",
        workPeriod: [], // 清空工作时间
        workResume: "", // 清空工作简历
        workResume: "请输入工作简历内容，可自由编辑", // 清空工作简历
      };
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        certNumber: null,
        gender: null,
        phone: null,
        unitName: null,
        contact: null,
        unitPhonenumber: null,
        trainingType: null,
        subject: null,
        class: null,
        paymentStatus: null,
        recordStatus: null,
        submitStatus: null,
        isQualified: null,
        registerTime: null,
        remark: null,
      };

      // 安全地调用 resetFields，确保引用存在
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
  },
  watch: {
    // 根据名称筛选部门树
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>

<style scoped>
.app-container {
  display: flex;
}
.el-col {
  height: 100%;
}
.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 4px;
}

.dialog-person-registration ::v-deep .el-dialog__header {
  text-align: center;
}
.dialog-collective-registration ::v-deep .el-dialog__header {
  text-align: center;
}
.dialog-collective-registration ::v-deep .el-dialog {
  /* min-height: 600px; */
  /* 最大高度为视窗高度的90% */
  /* max-height: 90vh;  */
}
.dialog-collective-registration ::v-deep .el-dialog__body {
  /* 减去头部和底部的高度 */
  /* max-height: calc(90vh - 120px);  */
  overflow-y: auto; /* 超出时显示滚动条 */
}

/* 备注弹窗样式 */
.dialog-remark ::v-deep .el-dialog__header {
  text-align: center;
}

.dialog-remark ::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

.dialog-remark ::v-deep .el-table td {
  padding: 10px;
}

.dialog-remark ::v-deep .el-textarea {
  resize: none;
}

/* 调整表格位置 */
.dialog-remark ::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

/* 确保表格在左上角 */
.dialog-remark ::v-deep .el-form-item__label {
  padding-right: 0;
}

/* 调整按钮位置 */
.dialog-remark ::v-deep .dialog-footer {
  text-align: right;
  padding: 20px 30px 30px;
}

/* 确保内容区域正确显示 */
.dialog-remark ::v-deep .el-dialog__body {
  padding: 20px 30px;
}

.dialog-submit-application ::v-deep .el-dialog__header {
  text-align: center;
}
</style>
